//
//  FR_MessageListViewController.m
//  FaceRecognition
//
//  Created by Sylar on 2017/7/6.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "FR_MessageListViewController.h"
#import "FR_MessageListCell.h"
#import "FR_MessageModel.h"
#import "SY_Activity.h"
#import "SY_Activity_Model.h"
#import "FR_EnterAndLeaveMessageController.h"
#import "SYMessageTool.h"

@interface FR_MessageListViewController ()<UITableViewDelegate,UITableViewDataSource>

{
   NSInteger pageNO;
}
@property (nonatomic, strong) UILabel *emptyLabel;
@property (nonatomic, strong) UITableView *messageTable;
@property (nonatomic, strong) NSMutableArray *messageArr;
@property (nonatomic, assign) NSInteger pageNum;

/**从通知列表启动app，查看了消息后，只能传过来Infoid，不知道消息id,所以先把infoid保存起来，在请求完列表后，在对比Infoid 改变状态*/
@property (nonatomic, strong) NSString *messageid;

@end

@implementation FR_MessageListViewController

- (id)init
{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = NO;
        
    }
    return self;
}

- (void)loadView {
    [super loadView];
    
    self.navBar.nav_titleLabel.text = @"消息";
    [self.view setBackgroundColor:colorFromHex(@"f4f5f7")];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];

//    [self.messageArr removeAllObjects];
//    [self loadMessageListDataFromDB:0];
}

- (NSMutableArray *)messageArr{
   
   if (_messageArr == nil) {
      
      _messageArr = [NSMutableArray array];
   }
   
   return _messageArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.messageTable];
    
    //[self getMessageListRequest];
    
    self.emptyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, SCREENWIDTH, 17)];
    [self.emptyLabel setText:@"暂无消息"];
    [self.emptyLabel setTextColor:colorFromHex(@"979797")];
    [self.emptyLabel setFont:[UIFont systemFontOfSize:17]];
    [self.emptyLabel setHidden:YES];
    [self.emptyLabel setTextAlignment:NSTextAlignmentCenter];
    [self.messageTable addSubview:self.emptyLabel];
   
   pageNO = 0;
   
   NSArray * arr  = [SYMessageTool getMessageListArrayFrom:0];
   
   if (arr.count > 0) {
      
      [self.emptyLabel setHidden:YES];
      
   }else{
      
      [self.emptyLabel setHidden:NO];
   }
   [self.messageArr addObjectsFromArray:arr];
   [self.messageTable reloadData];
   
   //收到通知就刷新列表
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNOtificationMessageListDataFromDB) name:@"refreshMessageList" object:nil];
    //从其他地方阅读消息详情的通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasReadMsg:) name:@"hasReadMsgDetail" object:nil];
}

- (void)loadMessageListDataFromDB:(NSInteger)pageNumber{
   
   NSLog(@"pageNumber = %ld",pageNumber);
   
   NSInteger fromindex = pageNumber * 10;
   NSArray * arr  = [SYMessageTool getMessageListArrayFrom:fromindex];
   [self.messageArr addObjectsFromArray:arr];
   [self.messageTable reloadData];
   
   if (arr.count > 0) {
      
      if (arr.count == 10) {
         
         [self.messageTable.mj_footer endRefreshing];
         
      }else{
         
         [self.messageTable.mj_footer endRefreshingWithNoMoreData];
      }
      
   }else{
      
       [self.messageTable.mj_footer endRefreshingWithNoMoreData];
   }
  
   

}

- (void)refreashMessageListDataFromDB:(NSInteger)pageNumber{

   NSArray * arr  = [SYMessageTool getMessageListArrayFrom:pageNumber];
   
   if (arr.count > 0) {
      
      [self.emptyLabel setHidden:YES];
      
   }else{
      
      [self.emptyLabel setHidden:NO];
   }
   
   [self.messageArr addObjectsFromArray:arr];
   [self.messageTable reloadData];
   [self.messageTable.mj_header endRefreshing];
   [self.messageTable.mj_footer endRefreshing];
   
  
   
}

- (void)loadNOtificationMessageListDataFromDB{
   
   pageNO =0;
   [self.messageArr removeAllObjects];
   NSArray * arr  = [SYMessageTool getMessageListArrayFrom:0];
   
   if (arr.count > 0) {
      
      [self.emptyLabel setHidden:YES];
      [self.messageArr addObjectsFromArray:arr];
      
   }else{
      
      [self.emptyLabel setHidden:NO];
   }
   
   [self.messageTable reloadData];
   [self.messageTable.mj_footer endRefreshing];
   
 
}

- (BOOL)prefersStatusBarHidden{
   
   return NO;
   
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
   
    [super didReceiveMemoryWarning];
    
}

//#pragma mark -Notification
//- (void)hasReadMsg:(NSNotification *)noti {
//
//
//    SY_Activity_Model *model = (SY_Activity_Model *)noti.object;
//
//    if (!model) {
//        return;
//    }
//
//
//    _messageid = model.messageid; //先保存
//
//
//    [self.messageTable.mj_header beginRefreshing];
//
//
//
//    return;
//
//
//    int indexPathRow = 0;
//    BOOL flag = false; //未找到
//    for (SY_Activity_Model *msgModel in _messageArr) {
//
//        if ([msgModel.infoid isEqualToString: model.infoid]) {
//
////            //改成已读状态
//            if (msgModel.readState == 0) {
////                NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
////
////                [param setObject:[NSString stringWithFormat:@"%ld",msgModel.messageid] forKey:@"messageid"];
////
////                [Utils Java_get:@"api/setMessageState" parameters:param success:^(NSInteger recode, id jsonObject) {
////
////                    msgModel.readState = 1;
////
////                    [self.messageArr replaceObjectAtIndex:indexPathRow withObject:msgModel];
////                    [self.messageTable reloadData];
////
////                } failure:^(NSInteger recode, NSError *error) {
////
////                }];
//            }
//            flag = true;
//            break;
//        }
//
//        indexPathRow++;
//    }
//
//
//
//}

#pragma mark - Request
- (void)getMessageListRequest {
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:USERID forKey:@"userid"];
    [param setObject:@"1" forKey:@"pageno"];
    [param setObject:@"20" forKey:@"pagesize"];
    [param setObject:SCHOOLID forKey:@"scid"];
    
    [Utils noHUD_Java_get:@"api/getMessageList" parameters:param success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = (NSDictionary *)jsonObject;
        
        NSArray *arr = [dic objectForKey:@"re_data"];
        
        self.pageNum = 1;//重置分页
        
        if (arr.count > 0) {
            [self.emptyLabel setHidden:YES];
            [self.messageTable setHidden:NO];
            self.messageArr = [[NSMutableArray alloc]init];
            
            for (NSDictionary *dict in arr) {
                FR_MessageModel *model = [FR_MessageModel mj_objectWithKeyValues:dict];
                [self.messageArr addObject:model];
            }
            
            if (_messageid && [_messageid integerValue] > 0) { //有infoid 说明是从推送列表点进来的，已经看过详情了 遍历设置第一条为已读状态
                int index = 0;
                for (FR_MessageModel *model in self.messageArr) {
                    
                    if (model.messageid == [_messageid integerValue]) {
                        
                        if (model.readState == 0) {
                            NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
                            
                            [param setObject:[NSString stringWithFormat:@"%ld",model.messageid] forKey:@"messageid"];
                            
                            [Utils Java_get:@"api/setMessageState" parameters:param success:^(NSInteger recode, id jsonObject) {
                                
                                model.readState = 1;
                                
                                [self.messageArr replaceObjectAtIndex:index withObject:model];
                                _messageid = nil;
                                [self.messageTable reloadData];
                
                            } failure:^(NSInteger recode, NSError *error) {
                                
                            }];
                            
                            break;
                        }

                        
                        
                        index++;
                    }
                    
                }
            }
            
            
            
        }else {
            [self.emptyLabel setHidden:NO];
            [self.messageTable setHidden:YES];
        }
        [self.messageTable.mj_footer endRefreshing];
        [self.messageTable.mj_header endRefreshing];
        [self.messageTable reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        [self showHint:error.localizedDescription];
        [self.messageTable.mj_header endRefreshing];
    }];
}

- (void)loadMoreMessages {
    
    self.pageNum += 1;
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:USERID forKey:@"userid"];
    [param setObject:[NSString stringWithFormat:@"%ld",self.pageNum] forKey:@"pageno"];
    [param setObject:@"20" forKey:@"pagesize"];
    [param setObject:SCHOOLID forKey:@"scid"];
    
    [Utils noHUD_Java_get:@"api/getMessageList" parameters:param success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = (NSDictionary *)jsonObject;
        
        NSArray *arr = [dic objectForKey:@"re_data"];
        
        if (arr.count > 0) {
            
            for (NSDictionary *dict in arr) {
                FR_MessageModel *model = [FR_MessageModel mj_objectWithKeyValues:dict];
                [self.messageArr addObject:model];
            }
            
            [self.messageTable.mj_footer endRefreshing];
        }else {
            [self.messageTable.mj_footer endRefreshingWithNoMoreData];
            self.pageNum -= 1;
            
        }
        
        [self.messageTable reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        [self showHint:error.localizedDescription];
        self.pageNum -= 1;
        [self.messageTable.mj_footer endRefreshing];
    }];
    
}

#pragma mark - TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.messageArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FR_MessageListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    
    if (cell == nil) {
        cell = [[FR_MessageListCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cellIdentifier"];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    SY_Activity_Model *model = [self.messageArr objectAtIndex:indexPath.row];
    [cell creatCell:model];
    
    return cell;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
   
   return YES;
}

// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
   return UITableViewCellEditingStyleDelete;
}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
   
   SY_Activity_Model * model = [self.messageArr objectAtIndex:indexPath.row];
   
   if (editingStyle == UITableViewCellEditingStyleDelete) {
      
      [self.messageArr removeObjectAtIndex:indexPath.row];
      [SYMessageTool cleanDisk:model];
      [self.messageTable reloadData];
      
      if (self.messageArr.count > 0) {
         
         [self.emptyLabel setHidden:YES];
         
      }else{
         
         [self.emptyLabel setHidden:NO];
      }
   }
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
   return @"删除";
}



#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
   
    SY_Activity_Model *msgModel = [self.messageArr objectAtIndex:indexPath.row];
    SY_Activity_Model *model = [[SY_Activity_Model alloc]init];
    model.apptype = 2;
    model.msgid = msgModel.msgid;
    model.infoid = msgModel.infoid;
    model.moveto = msgModel.moveto;
    model.classid = msgModel.classid;
    model.scid = msgModel.scid;
    model.description2 = msgModel.description2;
   if (model.moveto >= 25 && model.moveto <= 33) {
      
      
   }else{
      
      [SY_Activity shareActivity].instructionArr = @[model];
      [[SY_Activity shareActivity] action];
   }

   SY_Activity_Model * model2 = [[SY_Activity_Model alloc]init];
   model2.readState = 1;
   model2.infoid = msgModel.infoid;
   model2.description2 = msgModel.description2;
   
   [SYMessageTool updataMessageModel2:model];
   
   msgModel.readState = 1;
   
   [self.messageArr replaceObjectAtIndex:indexPath.row withObject:msgModel];
   [self.messageTable reloadData];
}

#pragma mark - Get

- (UITableView *)messageTable {
    
    if (_messageTable == nil) {
        _messageTable = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight - SafeAreaBottomHeight-49) style:(UITableViewStylePlain)];
        _messageTable.delegate = self;
        _messageTable.dataSource = self;
        _messageTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _messageTable.rowHeight = 131.0;
        [_messageTable setBackgroundColor:colorFromHex(@"f4f5f7")];
        _messageTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

            pageNO = 0;
            [self.messageArr removeAllObjects];
            [self refreashMessageListDataFromDB:pageNO];
        }];
        _messageTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

            pageNO ++;
            [self loadMessageListDataFromDB:pageNO];
        }];
    }
    return _messageTable;
}


@end
